<template>
    <div class="container">
        <iSearch>
            <template #Button>
                <a-button type="primary" @click="initList">刷新</a-button>
                <a-button type="primary" danger v-iscan="['auth:role:add']" @click="handleAdd">添加</a-button>
            </template>
        </iSearch>

        <iTable :pagination="false" :columns="columns" :tableData="tableData" :loading="loading">
            <template #state="{ record }">
                <a-tag :color="FuncDbAdminRoleState(record.state || 0).color">{{ FuncDbAdminRoleState(record.state || 0).label }}</a-tag>
            </template>
            <template #operate="{ record }">
                <a-flex gap="small" horizontal v-if="record.id !== 1">
                    <a-button type="link" v-iscan="['auth:role:edit']" @click="handleEdit(record.id)">编辑</a-button>
                    <iDelete :auth="['auth:role:del','disabled']" @delete="handleDelete(record.id)"></iDelete>
                </a-flex>
            </template>
        </iTable>
        

        <a-drawer :title="(formState.id || 0) > 0 ? '编辑角色': '添加角色'" rootClassName="full-modal-drawer" width="40%" :open="EditVisible" @close="handleEditClose()" :loading="EditLoading">
            <a-form ref="formStateRef" :model="formState" autocomplete="off" :rules="formStateRule" layout="vertical">
                <a-form-item name="role_name" label="角色名称">
                    <a-input v-model:value="formState.role_name" placeholder="请输入角色名称"></a-input>
                </a-form-item>
                <a-form-item name="state" label="状态">
                    <a-radio-group v-model:value="formState.state" name="State">
                        <a-radio v-for="(item,index) in DbAdminRoleState" :key="index" :value="item.value">{{ item.label }}</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item name="menuId" label="菜单权限">
                    <a-tree v-model:checkedKeys="formState.menu_id" checkable :tree-data="AuthMenuList" defaultExpandAll class="third-layer">
                        <template #title="{ title }">
                            <span>{{ title }}</span>
                        </template>
                    </a-tree>
                </a-form-item>
            </a-form>
            <template #extra>
                <a-space>
                    <a-button @click="handleEditClose()">取消</a-button>
                    <a-button type="primary" @click="handleSubmit()">保存</a-button>
                </a-space>
            </template>
        </a-drawer>
    </div>
</template>


<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { iPb } from '@/protobuf/interface/index'
import { ListAdminRole, ReadAdminRole, CreateAdminRole, UpdateAdminRole, DeleteAdminRole } from '@/api/admin_role';
import { FormInstance } from 'ant-design-vue';
import type { TreeProps, TableColumnsType } from 'ant-design-vue';
import { DbAdminRoleState, FuncDbAdminRoleState } from '@/tool/const'
import { Message } from '@/tool/antdv';
import { useStore } from '@/stores/index'
import { TableWidth } from '@/tool/enum';
const store = useStore()

const formStateRef = ref<FormInstance>()
const formState = ref<iPb.IDbAdminRole>(iPb.DbAdminRole.create())
const formStateRule = {
    role_name: [
        { required: true, message: '请输入角色名称' }
    ],
    State: [
        { required: true, message: '请选择状态' }
    ],
    MenuId: [
        { required: true, message: '请选择菜单权限' }
    ],
}

const loading = ref<Boolean>(false)
const EditVisible = ref<Boolean>(false)
const EditLoading = ref<Boolean>(false)
const AuthMenuList = ref<TreeProps['treeData']>()

const tableData = ref<Array<iPb.IDbAdminRole>>([])

    

const handleAdd = () => {
    formStateRef.value?.resetFields()
    formState.value = iPb.DbAdminRole.create()
    EditVisible.value = true
}
const handleEditClose = () => {
    EditVisible.value = false
}


const handleDelete = (id: number) => {
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    DeleteAdminRole(iPb.Admin.DeleteAdminRoleRequest.create({
        id: id
    })).then((_result: iPb.Admin.IDeleteAdminRoleResponse) => {
        EditLoading.value = false
        Message.success({
            content: "删除成功",
        })
        initList()
    })
}


const handleEdit = (id: number) => {
    formStateRef.value?.resetFields()
    if(EditLoading.value) {
        return
    }
    EditLoading.value = true
    const ReadAdminRoleRequest = iPb.Admin.ReadAdminRoleRequest.create({
        id: id
    })
    ReadAdminRole(ReadAdminRoleRequest).then((result:iPb.IDbAdminRole) => {
        formState.value = iPb.DbAdminRole.create(result)
        EditVisible.value = true
        EditLoading.value = false
    }).catch(() => {
        EditLoading.value = false
    })
}

const handleSubmit = () => {
    const formData = formState.value
    formStateRef.value?.validate().then(() => {
        if(EditLoading.value) {
            return
        }
        EditLoading.value = true
        if((formData.id || 0) > 0) {
            UpdateAdminRole(formData).then((_result:iPb.Admin.IUpdateAdminRoleResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "保存成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }else {
            CreateAdminRole(formData).then((_result:iPb.Admin.ICreateAdminRoleResponse) => {
                EditLoading.value = false
                EditVisible.value = false
                Message.success({
                    content: "添加成功",
                })
                initList()
            }).catch(() => {
                EditLoading.value = false
            })
        }
    })
    

}

const initList = () => {
    if(loading.value) {
        return
    }
    loading.value = true
    ListAdminRole(iPb.Admin.ListAdminRoleRequest.create()).then((result:iPb.Admin.IListAdminRoleResponse) => {
        let R = iPb.Admin.ListAdminRoleResponse.create(result)
        tableData.value = R.data
        loading.value = false
    })
}

const initMenuList = () => {
    let menu = filterMenu(store.ListMenu[0].children)
    AuthMenuList.value = menu
}


const filterMenu = (menu = []): TreeProps['treeData'] => {
    return menu.map((item: any) => {
        let obj: any = {
            key: item.meta.id,
            title: item.meta.title,
            children: []
        }
        if(item.children && item.children.length > 0) {
            obj.children = filterMenu(item.children)
        }else {
            if(item.meta.level == 2) {
                obj.class = "last-layer"
            }
        }
        return obj
    })
}


const columns:TableColumnsType = [
    {
        title: "ID",
        dataIndex: "id",
        width: TableWidth.Id,
    },
    {
        title: "角色名称",
        dataIndex: "role_name",
        width: TableWidth.Ordinary,
    },
    {
        title: "状态",
        dataIndex: "state",
        width: TableWidth.State,
    },
    {
        title: "操作",
        dataIndex: "operate",
        width: TableWidth.Operate,
    }
]

onMounted(() => {
    initList()
    initMenuList()
})


</script>


<style lang="less">
.third-layer {
    .ant-tree-list-holder-inner {
        display: inline-block !important;
    }
}
.last-layer {
    display: inline-flex !important;
}
</style>
